package tau.dimes.web;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;

import javax.servlet.ServletContext;

public class UserFiles
{
	private final String userpath;

	public UserFiles(String username, ServletContext context)
	{
		this.userpath = context.getRealPath("/users/" + username + "/files");
	}

	public String[] listFiles(final String fileType)
	{
		File filesDir = new File(userpath);

		if (!filesDir.exists() || !filesDir.isDirectory())
			return new String[0];

		String[] filesArray = filesDir.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name)
			{
				return (name.toLowerCase().endsWith(fileType.toLowerCase()));
			}
		});
		
		return filesArray;
	}
	
	public boolean exists(String filename)
	{
		File filesDir = new File(userpath);
		
		if (!filesDir.exists() || !filesDir.isDirectory())
			return false;
		
		File file = new File(filesDir, filename);
		return file.exists();
	}
	
	public File getFile(String filename) throws FileNotFoundException
	{
		File fileUserpath = new File(userpath);
		if (!fileUserpath.exists())
			fileUserpath.mkdirs();
		File file = new File(fileUserpath, filename);
		return file;
	}
}
